using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BezierCurveRenderer : MonoBehaviour
{
    public Transform[] controlPoints;
    public int segments = 30;
    private LineRenderer lineRenderer;
    private void Start()
    {
        lineRenderer = GetComponent<LineRenderer>();
        lineRenderer.positionCount = segments + 1;
       // DrawCubicBezier();
    }
    private void Update()
    {
        DrawCubicBezier();
    }
    void DrawCubicBezier()
    {
        for (int i = 0; i <= segments; i++)
        {
            float t = i / (float)segments;
            Vector3 point = CalculateCubicBezierPoint(t,
                controlPoints[0].position,
                controlPoints[1].position,
                controlPoints[2].position,
                controlPoints[3].position);
            lineRenderer.SetPosition(i, point);
        }
    }
    Vector3 CalculateCubicBezierPoint(float t, Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3)
    {
        // 三次贝塞尔曲线公式
        float u = 1 - t;
        float tt = t * t;
        float uu = u * u;
        float uuu = uu * u;
        float ttt = tt * t;
        Vector3 p = uuu * p0;
        p += 3 * uu * t * p1;
        p += 3 * u * tt * p2;
        p += ttt * p3;
        return p;
    }
}